package bagu.juc.threadpool;

import java.util.concurrent.*;

public class ThreadPoolExecutorsDemo01 {
    public static void main(String[] args) {
        //ThreadPoolExecutorTest();
        ExecutorTest();
    }

    /**
     * 使用ThreadPoolExecutor类创建线程池
     */
    private static void ThreadPoolExecutorTest() {
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                5,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(), // 任务队列
                Executors.defaultThreadFactory(), // 线程工厂
                new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );
        // 提交任务
        for (int i = 0; i < 100; i++) {
            final int task = i + 1;
            threadPool.execute(()->{
                String name = Thread.currentThread().getName();
                System.out.println("task-" + task + "is executed by " + "thread-" + name);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });

        }
        threadPool.shutdown();
    }

    /**
     * 使用Executor工具类创建线程池
     */
    public static void ExecutorTest(){
        ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 20; i++) {
           final int task = i + 1;
           fixedThreadPool.submit(()->{
               String name = Thread.currentThread().getName();
               System.out.println("task-" + task + " is executed by " + "thread-" + name);
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           });
        }
    }


}
